package com.yuqiangz.lock;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 赵雨强
 * @create 2021/7/10 15:56
 * @description 集合线程不安全演示
 */
public class ThreadDemo4 {

    /**
     * 不安全
     */
    private static List<String> list1 = new ArrayList<>();

    /**
     * 安全
     */
    private static List<String> list2 = new Vector<>();
    private static List<String> list3 = Collections.synchronizedList(new ArrayList<>());
    private static List<String> list4 = new CopyOnWriteArrayList<>();


    /**
     * 不安全
     */
    private static Set<String> set1 = new HashSet<>();
    /**
     * 安全
     */
    private static Set<String> set2 = new CopyOnWriteArraySet<>();


    /**
     * 不安全
     */
    private static Map<String, String> map1 = new HashMap<>();
    /**
     * 安全
     */
    private static Map<String, String> map2 = new ConcurrentHashMap<>();



    public static void main(String[] args) throws InterruptedException {
        // collection(list4);

        // CopyOnWriteArrayList解决
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i <30; i++) {
            new Thread(()->{
                //向集合添加内容
                list.add(UUID.randomUUID().toString().substring(0,8));
                //从集合获取内容
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

    public static void collection(Object ob){
        for (int i = 0; i <30; i++) {
            String key = String.valueOf(i);
            new Thread(()->{
                if(ob instanceof Collection){
                    Collection collection = (Collection)ob;
                    //向集合添加内容
                    collection.add(UUID.randomUUID().toString().substring(0,8));
                    //从集合获取内容
                    System.out.println(collection);
                } else if(ob instanceof Map){
                    Map map = (Map)ob;
                    //向集合添加内容
                    map.put(key,UUID.randomUUID().toString().substring(0,8));
                    //从集合获取内容
                    System.out.println(map);
                }
            },key).start();
        }
    }
}
